package cn.com.jdyun.controller;

import cn.com.jdyun.dto.UserCredit;
import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.interceptor.Auth;
import cn.com.jdyun.util.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    @Value("${spring.servlet.multipart.location}")
    private String filePath;

    /**
     * 处理文件上传
     *
     * @param file    文件对应字段
     * @param request
     * @param session
     * @return
     * @throws BdexGatewayException
     */
    @Auth
    @PostMapping(value = "/upload")
    public Map<String, Object> uploadImg(@RequestParam("file") MultipartFile file,
                                         HttpServletRequest request, HttpSession session) throws BdexGatewayException {
        String contentType = file.getContentType();
        if (!contentType.equalsIgnoreCase("image/png") &&
                !contentType.equalsIgnoreCase("image/jpeg")
                && !contentType.equalsIgnoreCase("image/gif")) {
            throw new BdexGatewayException("It's not a image file");
        }
        String fileName = file.getOriginalFilename();
        System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);
        Map<String, Object> result = null;
        try {
            UserCredit user = (UserCredit) session.getAttribute(Constant.ACCOUNT_Mining);
            result = uploadFile(user, file);
        } catch (Exception e) {
            // TODO: handle exception
        }
        //返回json
        return result;
    }

    private Map<String, Object> uploadFile(UserCredit user, MultipartFile sourceFile) throws Exception {
        Map<String, Object> result = new HashMap<>();
        //文件内容
        byte[] file = sourceFile.getBytes();
        //文件名称
        String fileName = sourceFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String fileNewName = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase() + suffix;
        if (!filePath.endsWith("/")) {
            filePath += "/";
        }
        String path = dateFormat.format(System.currentTimeMillis()) + "/" + user.getCode();
        File targetFile = new File(filePath + path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        path = path + "/" + fileNewName;
        FileOutputStream out = new FileOutputStream(filePath + path);
        out.write(file);
        out.flush();
        out.close();
        //文件原名称
        result.put("fileName", fileName);
        //访问路径（相对于站点）
        result.put("path", "/pic/" + path);
        return result;
    }
}
